package me.pinion.service

import com.jfinal.plugin.activerecord.Db;
import me.pinion.model.User;
import me.pinion.model.XModel
import me.pinion.model.message.Message
import me.pinion.model.message.MessageStatus;
import me.pinion.model.message.MessageType

import java.sql.Timestamp;

public class MessageService extends Service{
    private static MessageService ourInstance = new MessageService();

    public static MessageService getInstance() {
        return ourInstance;
    }

    private MessageService() {}

    public Message sendMessage(User sender, User reciver, MessageType type, XModel<? extends XModel> source, String content = ""){

        def message = new Message()
        message.setAttrs([
                sender          : sender.id,
                reciver         : reciver.id,
                msg_type        : MessageType.getTypeId(type),
                source_id       : source.id,
                source_type_id  : source.modelId,
                create_time     : new Timestamp(new Date().time),
                status          : MessageStatus.UNREAD.name(),
                content         : content
        ])
        message.save()
        return message;
    }

    public int count(User user){
        return Db.findFirst("SELECT count(id) AS 'count' FROM message WHERE reciver=?", user.id).getLong("count").intValue()
    }

    public List<Message> listByReciver(User user, MessageStatus status = MessageStatus.UNREAD){
        return Message.dao.find("SELECT m.* FROM message AS m WHERE m.reciver=? AND m.status=?", user.id, status.name())
    }
}
